package com.server.model.all.util;


import cn.hutool.core.util.ObjectUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TreeUtils<T extends TreeSelect<T>> {

    public static TreeUtils builder(){
        return new TreeUtils();
    }

    public List<T> buildTreeSelect(List<T> list) {
        List<T> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<>();
        for (T t : list) {
            tempList.add(t.getId());
        }
        for (Iterator<T> iterator = list.iterator(); iterator.hasNext(); ) {
            T t = iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(t.getParentId())) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        if (returnList.isEmpty()) {
            returnList = list;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<T> list, T t) {
        // 得到子节点列表
        List<T> childList = getChildList(list, t);
        t.setChildren(childList);
        for (T tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<T> getChildList(List<T> list, T t) {
        List<T> tlist = new ArrayList<>();
        Iterator<T> it = list.iterator();
        while (it.hasNext()) {
            T n = it.next();
            if (!ObjectUtil.isEmpty(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<T> list, T t) {
        return !getChildList(list, t).isEmpty();
    }

}
